#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
UDP传感器数据模拟器
用于模拟发送传感器数据到UDP服务器
"""

import socket
import json
import time
import random
import argparse
from datetime import datetime

# 传感器配置 (与实际应用中的sensor.py保持一致)
SENSOR_CONFIG = {
    "时间": {"id": 1, "min": 0, "max": 0, "step": 0},
    "GPSX": {"id": 2, "min": 0, "max": 100, "step": 0.1},
    "GPSY": {"id": 3, "min": 0, "max": 100, "step": 0.1},
    "航速(节)": {"id": 4, "min": 0, "max": 30, "step": 0.5},
    "温度(度)": {"id": 5, "min": -10, "max": 40, "step": 0.5},
    "风速(级)": {"id": 6, "min": 0, "max": 12, "step": 1},
}

class UdpSimulator:
    """UDP客户端模拟器"""
    
    def __init__(self, host='127.0.0.1', port=12345, interval=1.0):
        """
        初始化UDP模拟器
        
        参数:
            host: 目标主机地址
            port: 目标端口
            interval: 发送间隔（秒）
        """
        self.host = host
        self.port = port
        self.interval = interval
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.running = False
        
        # 初始传感器值
        self.values = {}
        for name, config in SENSOR_CONFIG.items():
            if name == "时间":
                self.values[config["id"]] = datetime.now().strftime('%H:%M:%S')
            else:
                self.values[config["id"]] = (config["min"] + config["max"]) / 2
    
    def start(self):
        """启动模拟器"""
        self.running = True
        try:
            print(f"UDP模拟器已启动，发送数据到 {self.host}:{self.port}")
            print("按Ctrl+C停止...")
            
            while self.running:
                self._update_values()
                self._send_all_sensors()
                time.sleep(self.interval)
                
        except KeyboardInterrupt:
            print("\n模拟器已停止")
        finally:
            self.sock.close()
    
    def stop(self):
        """停止模拟器"""
        self.running = False
        
    def _update_values(self):
        """更新传感器值"""
        for name, config in SENSOR_CONFIG.items():
            sensor_id = config["id"]
            
            if name == "时间":
                # 更新时间
                self.values[sensor_id] = datetime.now().strftime('%H:%M:%S')
            else:
                # 随机增减值
                current = self.values[sensor_id]
                step = config["step"]
                change = random.uniform(-step*2, step*2)
                new_value = current + change
                
                # 确保在范围内
                new_value = max(config["min"], min(config["max"], new_value))
                # 保留两位小数
                self.values[sensor_id] = round(new_value, 2)
    
    def _send_all_sensors(self):
        """发送所有传感器数据"""
        for sensor_id, value in self.values.items():
            self._send_data(sensor_id, value)
    
    def _send_data(self, sensor_id, value):
        """发送单个传感器数据"""
        # 创建JSON格式数据
        data = {
            "id": sensor_id,
            "value": value
        }
        
        # 编码为JSON字符串
        json_data = json.dumps(data)
        
        # 发送UDP包
        self.sock.sendto(json_data.encode('utf-8'), (self.host, self.port))
        print(f"已发送: ID={sensor_id}, 值={value}")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="UDP传感器数据模拟器")
    parser.add_argument("--host", default="127.0.0.1", help="目标主机地址")
    parser.add_argument("--port", type=int, default=12345, help="目标端口")
    parser.add_argument("--interval", type=float, default=1.0, help="发送间隔（秒）")
    
    args = parser.parse_args()
    
    simulator = UdpSimulator(host=args.host, port=args.port, interval=args.interval)
    simulator.start()

if __name__ == "__main__":
    main()
